package core.plugins;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

public class UPCDatabase_org implements IProductIDPlugin 
{

	/**
	 * The next Plugin in the Chain of responsibility
	 */
	IProductIDPlugin nextPlugin;
	private int startIndex = 37;
	/**
	 * Default Constructor
	 */
	UPCDatabase_org()
	{
		nextPlugin = null;
	}
	
	@Override
	public String idProduct(String barcode)
	{
		String productDescription = upcDatabaseLookup(barcode);
		
		if (productDescription != null)
		{
			return productDescription;
		}
		else
		{
			//get next productID in chain
			IProductIDPlugin next = getNextPlugin();
			if (next != null)
			{
				return next.idProduct(barcode);
			}
			else
			{
				return null;
			}
		}
	}

	@Override
	public void setNextPlugin(IProductIDPlugin nextPlugin)
	{
		this.nextPlugin = nextPlugin;
	}

	@Override
	public IProductIDPlugin getNextPlugin()
	{
		return nextPlugin;
	}

	/**
	 * This method actually takes the barcode and checks the specified
	 * database for the product.  If it finds the product it returns a
	 * String containing the description of the product. Otherwise this
	 * method will return null. 
	 * 
	 * @param barcode The barcode of the product to search for
	 * @return String containing the product Descritption.  If the 
	 * 		product is not found, or there is an error then null is
	 * 		returned.
	 */
	private String upcDatabaseLookup(String barcode)
	{
		String url = "http://www.upcdatabase.com/item/"+barcode;
		try 
		{
			URL databaseURL = new URL(url);
			BufferedReader in;
			in = new BufferedReader(
				 new InputStreamReader(databaseURL.openStream()));
			

			String inputLine;
			while ((inputLine = in.readLine()) != null)
			{
			        if(inputLine.contains("Description"))
			        {

			    		in.close();
			        	return findDescription(inputLine);
			        }
			}
			in.close();			
			
		} 
		catch (MalformedURLException e) 
		{
		}
		catch (IOException e) 
		{
		}
		
		return null;
	}
	
	private String findDescription(String _inputLine) throws IOException
	{
		String inputLine = _inputLine;
		
		        if(inputLine.contains("Description"))
		        {
		        	int endIndex = inputLine.lastIndexOf("</td>");
		        	String description = (String) inputLine.subSequence(startIndex, endIndex);
		        	return description;
		        }
		
		return null;
	}
}
